/*
 * DAO.java
 *
 * Created on 8 de agosto de 2007, 05:07 PM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */
package ejb.metrica.seguridad.dao;

import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

/**
 *
 * @author jsanchez
 * Es una clase basicas que define los metodos basicos que debe tener una implementacion de un dao
 */
public abstract class DAO {

    //variables basicas de administracion de la conexion a igformato
    protected java.sql.Connection conn = null;
    protected java.sql.PreparedStatement prep = null;
    protected java.sql.ResultSet resul = null;
    protected java.sql.PreparedStatement prep1 = null;
    protected java.sql.ResultSet resul1 = null;

    //metodos basicos para implememtar en cada uno de los daos para las tablas de igformato
    public abstract Object buscar(Integer id) throws Exception;

    public abstract java.util.Collection buscarTodos() throws Exception;

    public abstract Integer guardar(Object obj) throws Exception;

    public abstract void eliminar(Integer id) throws Exception;

    public abstract Object existe(Object obj) throws Exception;

    /**
     * Retorna una conexion independiente a la base de datos de IGFormato
     */
    public void getConnection() throws Exception {
        if (conn == null || conn.isClosed()) {
            Context ctx = new InitialContext();
            DataSource ds = (DataSource) ctx.lookup("java:/METRICADB");
            conn = ds.getConnection();
        }

    }
    
    /*public Cone getConnectionParam(){
        try {
            DataSource ds = (DataSource) new InitialContext().lookup("java:/METRICADW");
        } catch (NamingException ex) {
            Logger.getLogger(DAO.class.getName()).log(Level.SEVERE, null, ex);
        }
    }*/


    public Integer getMaximoId(String tabla) throws SQLException, Exception {
        java.sql.PreparedStatement prep3 = null;
        java.sql.ResultSet resul3 = null;
        try {
            prep3 = conn.prepareStatement("SELECT MAX(ID) FROM " + tabla.trim().toUpperCase());
            resul3 = prep3.executeQuery();
            if (resul3.next()) {
                return resul3.getInt(1) + 1;
            }
        } catch (java.sql.SQLException e) {
            throw e;
        } catch (Exception e) {
            throw e;
        } finally {
            try {
                prep3.close();
            } catch (Exception e) {
            }
            try {
                resul3.close();
            } catch (Exception e) {
            }
        }
        return null;
    }

    public void closeAll() {
        //        try{conn.close();}catch(Exception e){}
        try {
            prep.close();
        } catch (Exception e) {
        }
        try {
            resul.close();
        } catch (Exception e) {
        }
        try {
            prep1.close();
        } catch (Exception e) {
        }
        try {
            resul1.close();
        } catch (Exception e) {
        }
        try {
            conn.close();
        } catch (Exception e) {
        }        
    }

    public Object getDatos(java.sql.ResultSet res, Object DTO) throws SQLException, Exception {
        java.lang.reflect.Method[] atribC = DTO.getClass().getMethods();
        for (int i = 0; i < atribC.length; i++) {
            if (atribC[i].getName().startsWith("set") && !atribC[i].getName().startsWith("setID")) {
                String COLUMNA = atribC[i].getName().substring(3, atribC[i].getName().length());
                Object obj = null;
                try {
                    obj = res.getObject(COLUMNA);
                } catch (Exception e) {/*System.out.println("la columna >"+COLUMNA+"< no existe en la tabla");*/ }
                try {
                    if (obj != null) {
                        if (obj instanceof java.math.BigDecimal) {
                            if (((java.math.BigDecimal) obj).scale() <= 0) {
                                obj = Integer.valueOf(((java.math.BigDecimal) obj).intValue());
                            } else {
                                obj = Double.valueOf(((java.math.BigDecimal) obj).doubleValue());
                            }
                        }
                        atribC[i].invoke(DTO, obj);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    System.out.println("No se pudo invocar el metodos >" + atribC[i] + "< para asignarle el valor :" + obj);
                    throw e;
                }
            }
        }
        return DTO;
    }

    public void setDatos(java.sql.PreparedStatement pre, Object DTO, String nombreColumnasOrdenadas) throws SQLException, Throwable, Exception {
        java.lang.reflect.Method[] atribC = DTO.getClass().getMethods();
        String[] campos = nombreColumnasOrdenadas.split(",");
        Object[] obj = new Object[0];
        pre.clearParameters();
        for (int i = 0; i < atribC.length; i++) {
            if (atribC[i].getName().startsWith("get") && !atribC[i].getName().startsWith("getID")) {
                String COLUMNA = atribC[i].getName().substring(3, atribC[i].getName().length());
                for (int j = 0; j < campos.length; j++) {
                    if (COLUMNA.trim().toUpperCase().equals(campos[j].trim().toUpperCase())) {
                        campos[j]="_YA_PROCESADO_";
                        pre.setObject(j + 1, atribC[i].invoke(DTO, obj));
                    }
                }
            }
        }
    }
}
